import scrapy

from scrapy_dangdang_095.items import ScrapyDangdang095Item


class DangdangSpider(scrapy.Spider):
    name = "dangdang"
    allowed_domains = ["category.dangdang.com"]
    start_urls = ["https://category.dangdang.com/cp01.01.02.00.00.00.html"]

    base_url = 'https://category.dangdang.com/pg'
    page = 1

    def parse(self, response):
        #pipelines   下载数据
        #items       定义数据结构的
        # src = //*[@id="component_59"]/li//img/@src
        # alt = //*[@id="component_59"]/li//img/@alt
        # price = //*[@id="component_59"]/li//p[@class="price"]/span[1]/text()
        #所有的seletor的对象，都可以再次调用xpath方法
        li_list = response.xpath('//*[@id="component_59"]/li')

        for li in li_list:
            #src = li.xpath('.//img/@src').extract_first()
            src = li.xpath('.//img/@data-original').extract_first()     #  @data-original是懒加载
            #第一张图片不是懒加载，没有@data-original
            if src:
                src = src
            else:
                src = li.xpath('.//img/@src').extract_first()


            name = li.xpath('.//img/@alt').extract_first()
            price = li.xpath('.//p[@class="price"]/span[1]/text()').extract_first()

            book = ScrapyDangdang095Item(src = src, name = name, price = price)

            # 获取一个book就将book交给pipelines
            yield book


        # print('======================================')
        # print(src,name,price)
        # print('======================================')
        # pass


# 每一页的爬取业务逻辑都一样，我们只需要执行那个页面的请求再次调用parse方法就可以
#https://category.dangdang.com/pg2-cp01.01.02.00.00.00.html
#https://category.dangdang.com/pg3-cp01.01.02.00.00.00.html
#https://category.dangdang.com/pg4-cp01.01.02.00.00.00.html
        if self.page < 100:
            self.page = self.page + 1

            url = self.base_url + str(self.page) + '-cp01.01.02.00.00.00.html'

            #怎么调用parse方法
            #scrapy.Request就是scrapy的get请求
            yield scrapy.Request(url = url,callback = self.parse())